<template>
    <div class="city-manage-container">
      <!-- 搜索和操作区域 -->
      <div class="operation-area">
        <el-card shadow="hover">
          <div class="search-wrapper">
            <el-input
                v-model="searchQuery"
                placeholder="输入城市名称搜索"
                clearable
                class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
  
            <el-select v-model="scoreFilter" placeholder="评分筛选" clearable>
              <el-option label="全部" value="" />
              <el-option label="4.5分以上" :value="4.5" />
              <el-option label="4.0-4.5分" :value="4.0" />
              <el-option label="4.0分以下" :value="3.9" />
            </el-select>
  
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
          </div>
        </el-card>
      </div>
  
      <!-- 城市表格 -->
      <el-card shadow="hover" class="table-card">
        <el-table
            :data="filteredCityList"
            border
            stripe
            style="width: 100%"
            v-loading="loading"
        >
          <el-table-column type="index" width="50" label="序号" />
  
          <el-table-column label="城市图片" width="100">
            <template #default="scope">
              <el-image
                  :size="50"
                  :src="scope.row.coverImage || '/images/default-city.jpg'"
                  fit="cover"
                  style="width: 60px; height: 60px; border-radius: 4px;"
              />
            </template>
          </el-table-column>
  
          <el-table-column prop="name" label="城市名称" width="120" />
  
          <el-table-column prop="subtitle" label="副标题" width="180">
            <template #default="scope">
              {{ scope.row.subtitle || '未设置' }}
            </template>
          </el-table-column>
  
          <el-table-column prop="address" label="地址" width="150" />
  
          <el-table-column prop="touristNumber" label="年游客量" width="120">
            <template #default="scope">
              {{ formatNumber(scope.row.touristNumber) }}
            </template>
          </el-table-column>
  
          <el-table-column prop="spotNumber" label="景点数量" width="100" />
  
          <el-table-column prop="score" label="评分" width="100" sortable>
            <template #default="scope">
              <el-rate
                  v-model="scope.row.score"
                  disabled
                  text-color="#ff9900"
                  score-template="{value}"
                  :max="5"
                  :allow-half="true"
                  :show-score="true"
              />
            </template>
          </el-table-column>
  
          <el-table-column prop="population" label="人口" width="120">
            <template #default="scope">
              {{ formatNumber(scope.row.population) }}
            </template>
          </el-table-column>
  
          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                  size="small"
                  @click="handleViewCity(scope.row)"
                  type="primary"
                  link
              >
                查看
              </el-button>
  
              <el-button
                  size="small"
                  @click="handleEditCity(scope.row)"
                  type="primary"
                  link
                  v-if="isAdmin"
              >
                编辑
              </el-button>
  
              <el-button
                  size="small"
                  @click="handleDeleteCity(scope.row)"
                  type="danger"
                  link
                  v-if="isAdmin"
              >
                删除
              </el-button>
  
              <el-button
                  size="small"
                  @click="handleViewClimate(scope.row)"
                  type="info"
                  link
              >
                气候数据
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCities"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 城市详情对话框 -->
      <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'edit' ? '编辑城市' : '城市详情'"
          width="700px"
      >
        <el-form
            ref="cityFormRef"
            :model="cityForm"
            :rules="cityFormRules"
            label-width="100px"
            :disabled="dialogType === 'view'"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="城市名称" prop="name">
                <el-input v-model="cityForm.name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="城市代码" prop="code">
                <el-input v-model.number="cityForm.code" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="副标题" prop="subtitle">
                <el-input v-model="cityForm.subtitle" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input v-model="cityForm.address" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="年游客量" prop="touristNumber">
                <el-input-number v-model="cityForm.touristNumber" :min="0" :step="10000" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="景点数量" prop="spotNumber">
                <el-input-number v-model="cityForm.spotNumber" :min="0" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="评分" prop="score">
                <el-rate
                    v-model="cityForm.score"
                    :max="5"
                    :allow-half="true"
                    :show-score="true"
                    text-color="#ff9900"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人口" prop="population">
                <el-input-number v-model="cityForm.population" :min="0" :step="10000" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="纬度" prop="centerLat">
                <el-input-number v-model="cityForm.centerLat" :precision="6" :step="0.000001" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经度" prop="centerLng">
                <el-input-number v-model="cityForm.centerLng" :precision="6" :step="0.000001" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="面积(km²)" prop="area">
                <el-input-number v-model="cityForm.area" :min="0" :precision="2" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="货币" prop="currency">
                <el-input v-model="cityForm.currency" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-form-item label="语言" prop="language">
            <el-select
                v-model="cityForm.language"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入语言"
                style="width: 100%;"
            >
              <el-option label="普通话" value="普通话" />
              <el-option label="河北方言" value="河北方言" />
              <el-option label="晋语方言" value="晋语方言" />
              <el-option label="冀鲁官话" value="冀鲁官话" />
            </el-select>
          </el-form-item>
  
          <el-form-item label="最佳季节" prop="season">
            <el-select
                v-model="cityForm.season"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入最佳旅游季节"
                style="width: 100%;"
            >
              <el-option label="春季(3月-5月)" value="3月-5月" />
              <el-option label="夏季(6月-8月)" value="6月-8月" />
              <el-option label="秋季(9月-11月)" value="9月-11月" />
              <el-option label="冬季(12月-2月)" value="12月-2月" />
            </el-select>
          </el-form-item>
  
          <el-form-item label="封面图片" prop="coverImage">
            <el-upload
                class="image-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleCoverSuccess"
                :before-upload="beforeImageUpload"
            >
              <img v-if="cityForm.coverImage" :src="cityForm.coverImage" class="city-image" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
  
          <el-form-item label="主图片" prop="mainImage">
            <el-upload
                class="image-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleMainImageSuccess"
                :before-upload="beforeImageUpload"
            >
              <img v-if="cityForm.mainImage" :src="cityForm.mainImage" class="city-image" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
  
          <el-form-item label="城市描述" prop="description">
            <el-input v-model="cityForm.description" type="textarea" rows="4" />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
                type="primary"
                @click="submitCityForm"
                v-if="dialogType !== 'view'"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 气候数据对话框 -->
      <el-dialog
          v-model="climateDialogVisible"
          title="城市气候数据"
          width="800px"
      >
        <div v-if="selectedCity && selectedCity.climate">
          <el-tabs v-model="activeClimateTab">
            <el-tab-pane label="季节气候" name="seasons">
              <el-table :data="selectedCity.climate.seasons" border stripe>
                <el-table-column prop="name" label="季节名称" width="120" />
                <el-table-column prop="description" label="描述" />
                <el-table-column prop="temperature" label="温度范围" width="150" />
                <el-table-column prop="humidity" label="湿度" width="80" />
                <el-table-column prop="rainfall" label="降水" width="100" />
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="月度气候" name="months">
              <div style="height: 400px;" ref="monthlyChartContainer">
                <div id="monthly-chart" style="width: 100%; height: 400px;"></div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-else>
          该城市暂无气候数据
        </div>
      </el-dialog>
  
      <!-- 删除确认对话框 -->
      <el-dialog
          v-model="deleteDialogVisible"
          title="确认删除"
          width="400px"
      >
        <div class="delete-confirm">
          <el-icon class="warning-icon"><WarningFilled /></el-icon>
          <span>确定要删除城市 <strong>{{ selectedCity.name }}</strong> 吗？此操作不可恢复！</span>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="confirmDelete">确定删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { ref, reactive, computed, onMounted, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Plus, WarningFilled } from '@element-plus/icons-vue'
  import * as echarts from 'echarts'
  import { getAllCityDetail, deleteCityDetail, updateCityDetail } from '@/api/cityDetail'
  
  export default {
    name: 'CityManagement',
    components: {
      Search,
      Plus,
      WarningFilled
    },
    setup() {
      // 状态和数据
      const loading = ref(false);
      const cityList = ref([]);
      const searchQuery = ref('');
      const scoreFilter = ref('');
      const dialogVisible = ref(false);
      const dialogType = ref('view'); // 'view', 'edit'
      const deleteDialogVisible = ref(false);
      const climateDialogVisible = ref(false);
      const selectedCity = ref({});
      const currentPage = ref(1);
      const pageSize = ref(10);
      const totalCities = ref(0);
      const activeClimateTab = ref('seasons');
      const monthlyChartContainer = ref(null);
      const monthlyChart = ref(null);
  
      // 管理员权限判断
      const isAdmin = ref(true); // 假设当前用户是管理员
  
      // 城市表单
      const cityFormRef = ref(null);
      const cityForm = reactive({
        cityId: null,
        name: '',
        code: null,
        subtitle: '',
        touristNumber: 0,
        spotNumber: 0,
        score: 4.0,
        centerLat: 0,
        centerLng: 0,
        coverImage: '',
        mainImage: '',
        address: '',
        area: 0,
        population: 0,
        language: [],
        currency: '',
        season: [],
        description: '',
        climate: {
          seasons: [],
          months: []
        }
      });
  
      // 表单验证规则
      const cityFormRules = reactive({
        name: [
          { required: true, message: '请输入城市名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入城市代码', trigger: 'blur' },
          { type: 'number', message: '城市代码必须是数字', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入城市地址', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入城市描述', trigger: 'blur' }
        ]
      });
  
      // 根据过滤条件筛选城市
      const filteredCityList = computed(() => {
        if (!cityList.value) return [];
  
        return cityList.value.filter(city => {
          const matchQuery = searchQuery.value
            ? (city.name && city.name.includes(searchQuery.value)) ||
              (city.subtitle && city.subtitle.includes(searchQuery.value)) ||
              (city.address && city.address.includes(searchQuery.value))
            : true;
  
          const matchScore = scoreFilter.value !== ''
            ? scoreFilter.value === 4.5 
              ? city.score >= 4.5 
              : scoreFilter.value === 4.0 
                ? city.score >= 4.0 && city.score < 4.5
                : city.score < 4.0
            : true;
  
          return matchQuery && matchScore;
        });
      });
  
      // 格式化数字（万/亿）
      const formatNumber = (num) => {
        if (!num) return '0';
        if (num >= 100000000) {
          return (num / 100000000).toFixed(2) + '亿';
        } else if (num >= 10000) {
          return (num / 10000).toFixed(2) + '万';
        } else {
          return num.toString();
        }
      };
  
      // 获取城市列表
      const fetchCityList = () => {
        loading.value = true;
        getAllCityDetail()
          .then(response => {
            const { state, message, data } = response;
            if (state === 0 && data) {
              cityList.value = data;
              totalCities.value = data.length;
            } else {
              ElMessage.error(message || '获取城市列表失败');
            }
          })
          .catch(error => {
            console.error('获取城市列表出错:', error);
            ElMessage.error('获取城市列表失败');
          })
          .finally(() => {
            loading.value = false;
          });
      };
  
      // 搜索城市
      const handleSearch = () => {
        currentPage.value = 1;
        // 前端过滤，无需调用API
      };
  
      // 变更每页显示数量
      const handleSizeChange = (val) => {
        pageSize.value = val;
      };
  
      // 变更当前页码
      const handleCurrentChange = (val) => {
        currentPage.value = val;
      };
  
      // 查看城市
      const handleViewCity = (row) => {
        selectedCity.value = row;
        Object.assign(cityForm, JSON.parse(JSON.stringify(row)));
        dialogType.value = 'view';
        dialogVisible.value = true;
      };
  
      // 编辑城市
      const handleEditCity = (row) => {
        selectedCity.value = row;
        Object.assign(cityForm, JSON.parse(JSON.stringify(row)));
        dialogType.value = 'edit';
        dialogVisible.value = true;
      };
  
      // 删除城市
      const handleDeleteCity = (row) => {
        selectedCity.value = row;
        deleteDialogVisible.value = true;
      };
  
      // 查看气候数据
      const handleViewClimate = (row) => {
        selectedCity.value = row;
        climateDialogVisible.value = true;
        
        // 在对话框显示后初始化图表
        nextTick().then(() => {
          if (row.climate && row.climate.months && row.climate.months.length > 0) {
            initMonthlyChart(row.climate.months);
          }
        });
      };
  
      // 初始化月度气候图表
      const initMonthlyChart = (monthsData) => {
        if (monthlyChart.value) {
          monthlyChart.value.dispose();
        }
  
        const chartDom = document.getElementById('monthly-chart');
        if (!chartDom) return;
        
        monthlyChart.value = echarts.init(chartDom);
        
        const months = monthsData.map(item => item.name);
        const temperatures = monthsData.map(item => item.temperature);
        const rainfalls = monthsData.map(item => item.rainfall);
        
        const option = {
          title: {
            text: '月度气候数据',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          legend: {
            data: ['温度(°C)', '降水量(mm)'],
            bottom: '0%'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: months
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '温度(°C)',
              position: 'left',
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#5470C6'
                }
              }
            },
            {
              type: 'value',
              name: '降水量(mm)',
              position: 'right',
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#91CC75'
                }
              }
            }
          ],
          series: [
            {
              name: '温度(°C)',
              type: 'line',
              smooth: true,
              lineStyle: {
                width: 2,
                color: '#5470C6'
              },
              data: temperatures
            },
            {
              name: '降水量(mm)',
              type: 'bar',
              yAxisIndex: 1,
              itemStyle: {
                color: '#91CC75'
              },
              data: rainfalls
            }
          ]
        };
        
        monthlyChart.value.setOption(option);
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
          monthlyChart.value && monthlyChart.value.resize();
        });
      };
  
      // 确认删除
      const confirmDelete = () => {
        loading.value = true;
        deleteCityDetail(selectedCity.value.cityId)
          .then(response => {
            const { state, message } = response;
            if (state === 0) {
              ElMessage.success('删除成功');
              deleteDialogVisible.value = false;
              // 从列表中移除
              const index = cityList.value.findIndex(item => item.cityId === selectedCity.value.cityId);
              if (index !== -1) {
                cityList.value.splice(index, 1);
              }
            } else {
              ElMessage.error(message || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除城市出错:', error);
            ElMessage.error('删除失败');
          })
          .finally(() => {
            loading.value = false;
          });
      };
  
      // 提交城市表单
      const submitCityForm = () => {
        if (!cityFormRef.value) return;
  
        cityFormRef.value.validate((valid) => {
          if (valid) {
            loading.value = true;
            updateCityDetail(cityForm)
              .then(response => {
                const { state, message } = response;
                if (state === 0) {
                  ElMessage.success('更新成功');
                  dialogVisible.value = false;
                  // 更新列表中的数据
                  const index = cityList.value.findIndex(item => item.cityId === cityForm.cityId);
                  if (index !== -1) {
                    cityList.value[index] = { ...cityList.value[index], ...cityForm };
                  }
                } else {
                  ElMessage.error(message || '更新失败');
                }
              })
              .catch(error => {
                console.error('更新城市出错:', error);
                ElMessage.error('更新失败');
              })
              .finally(() => {
                loading.value = false;
              });
          }
        });
      };
  
      // 封面图片上传成功回调
      const handleCoverSuccess = (response, file) => {
        if (response.state === 0 && response.data) {
          cityForm.coverImage = response.data.url;
          ElMessage.success('封面图片上传成功');
        } else {
          ElMessage.error('封面图片上传失败');
        }
      };
  
      // 主图片上传成功回调
      const handleMainImageSuccess = (response, file) => {
        if (response.state === 0 && response.data) {
          cityForm.mainImage = response.data.url;
          ElMessage.success('主图片上传成功');
        } else {
          ElMessage.error('主图片上传失败');
        }
      };
  
      // 图片上传前的验证
      const beforeImageUpload = (file) => {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
  
        if (!isJPG && !isPNG) {
          ElMessage.error('图片只能是JPG或PNG格式!');
          return false;
        }
        if (!isLt2M) {
          ElMessage.error('图片大小不能超过2MB!');
          return false;
        }
        return true;
      };
  
      // 生命周期钩子
      onMounted(() => {
        fetchCityList();
      });
  
      return {
        loading,
        cityList,
        searchQuery,
        scoreFilter,
        dialogVisible,
        dialogType,
        deleteDialogVisible,
        climateDialogVisible,
        selectedCity,
        currentPage,
        pageSize,
        totalCities,
        isAdmin,
        cityFormRef,
        cityForm,
        cityFormRules,
        activeClimateTab,
        monthlyChartContainer,
        filteredCityList,
        formatNumber,
        handleSearch,
        handleSizeChange,
        handleCurrentChange,
        handleViewCity,
        handleEditCity,
        handleDeleteCity,
        handleViewClimate,
        confirmDelete,
        submitCityForm,
        handleCoverSuccess,
        handleMainImageSuccess,
        beforeImageUpload
      };
    }
  };
  </script>
  
  <style scoped>
  .city-manage-container {
    padding: 20px;
  }
  
  .operation-area {
    margin-bottom: 20px;
  }
  
  .search-wrapper {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  .search-input {
    width: 220px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .image-uploader {
    width: 120px;
    height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
  }
  
  .image-uploader:hover {
    border-color: #409EFF;
  }
  
  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  
  .city-image {
    width: 120px;
    height: 120px;
    display: block;
    object-fit: cover;
  }
  
  .delete-confirm {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .warning-icon {
    font-size: 24px;
    color: #E6A23C;
  }
  </style>